package com.hwadee.ems.controller;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;

import com.hwadee.ems.domain.dto.PageQuery;
import com.hwadee.ems.domain.dto.Result;
import com.hwadee.ems.domain.po.Classroom;
import com.hwadee.ems.domain.vo.ClassroomVO;
import com.hwadee.ems.service.IClassroomService;

/**
 * <p>
 * 教室 前端控制器
 * </p>
 *
 * @author EnosElinsa
 * @since 2024/06/21
 */
@Slf4j
@RestController
@RequestMapping("/classroom")
public class ClassroomController {

    @Resource
    private IClassroomService classroomService;

    @GetMapping("/page")
    public Result<IPage<ClassroomVO>> page(PageQuery pageQuery, 
        @RequestParam(required = false) String name, 
        @RequestParam(required = false) Integer category) {
        return classroomService.page(pageQuery, name, category);
    }

    @PostMapping
    public Result<Long> save(@RequestBody Classroom classroom) {
        if (classroomService.save(classroom)) {
            log.info("save classroom success, classroom id: {}", classroom.getId());
            return Result.ok(classroom.getId());
        } else {
            log.error("save classroom failed, classroom: {}", classroom);
            return Result.error();
        }
    }

    @PutMapping
    public Result<Void> updateById(@RequestBody Classroom classroom) {
        if (classroomService.updateById(classroom)) {
            log.info("update classroom success, classroom id: {}", classroom.getId());
            return Result.ok();
        } else {
            log.error("update classroom failed, classroom: {}", classroom);
            return Result.error();
        }
    }
    
    @DeleteMapping("/{id}")
    public Result<Void> removeById(@PathVariable Long id) {
        if (classroomService.removeById(id)) {
            log.info("remove classroom success, classroom id: {}", id);
            return Result.ok();
        } else {
            log.error("remove classroom failed, classroom id: {}", id);
            return Result.error();
        }
    }

    @GetMapping("/list")
    public Result<List<ClassroomVO>> list() {
        return Result.ok(
            classroomService.list()
                .stream()
                .map(ClassroomVO::new)
                .collect(Collectors.toList())
        );
    }

}
